package com.kh.rationaldrugreview.service;

import com.kh.rationaldrugreview.entity.Prescription;
import com.kh.rationaldrugreview.mapper.PrescriptionMapper;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import java.time.LocalDateTime;
import java.util.List;

@Service
@RequiredArgsConstructor
public class PrescriptionService {
    
    private final PrescriptionMapper prescriptionMapper;
    
    public List<Prescription> findAll() {
        return prescriptionMapper.findAll();
    }
    
    public Prescription findById(Long prescriptionId) {
        return prescriptionMapper.findById(prescriptionId);
    }
    
    public Prescription findByNumber(String prescriptionNumber) {
        return prescriptionMapper.findByNumber(prescriptionNumber);
    }
    
    public List<Prescription> findByPatientId(Long patientId) {
        return prescriptionMapper.findByPatientId(patientId);
    }
    
    public List<Prescription> findByDoctorName(String doctorName) {
        return prescriptionMapper.findByDoctorName(doctorName);
    }
    
    public List<Prescription> findByDepartment(String department) {
        return prescriptionMapper.findByDepartment(department);
    }
    
    public List<Prescription> findByDateRange(LocalDateTime startDate, LocalDateTime endDate) {
        return prescriptionMapper.findByDateRange(startDate, endDate);
    }
    
    /**
     * 保存或更新处方信息（内部使用，用于审查系统更新处方状态）
     */
    public Prescription save(Prescription prescription) {
        if (prescription.getPrescriptionId() == null) {
            prescription.setCreatedAt(LocalDateTime.now());
            prescription.setUpdatedAt(LocalDateTime.now());
            prescription.setIsActive(true);
            prescription.setIsReviewed(false);
            prescriptionMapper.insert(prescription);
        } else {
            prescription.setUpdatedAt(LocalDateTime.now());
            prescriptionMapper.update(prescription);
        }
        return prescription;
    }
    
    public int count() {
        return prescriptionMapper.count();
    }
}